/*
This file is part of IRCaBot.
IRCaBot is IRC logger with features.
Source code: https://notabug.org/acetone/ircabot.
Copyright (C) acetone, 2023.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "ircnetworkclientstarter.h"

#include <QThread>
#include <QDebug>
#include <QApplication>

QList<QPair<QSharedPointer<IRCNetworkClient>, QThread*>> IRCNetworkClientStarter::m_instanses;

void IRCNetworkClientStarter::run()
{
    if (not m_instanses.isEmpty())
    {
        qCritical() << "IRCNetworkClientStarter::run called, but instanses list not empty";
        return;
    }

    foreach (auto config, Config::networksAccess())
    {
        QSharedPointer<IRCNetworkClient> network (new IRCNetworkClient);
        QThread* thread = new QThread;
        network->moveToThread(thread);
        network->setConfig(config);
        m_instanses.push_back( {network, thread} );
        QObject::connect(thread, &QThread::started, network.data(), &IRCNetworkClient::start);
        QObject::connect(network.data(), &IRCNetworkClient::stopped, thread, &QThread::quit, Qt::DirectConnection);
        thread->start();
        qDebug().noquote() << "["+config->networkName+"]" << "Thread started";
    }
}

void IRCNetworkClientStarter::stop()
{
    foreach (auto inst, m_instanses)
    {
        inst.first->stop();
        qDebug().noquote() << "["+inst.first->m_config->networkName+"]" << "Shutdown requested";
        QApplication::sync();

        if (not inst.second->wait(1000))
        {
            qWarning().noquote() << "[Core] IRC network client thread not stopped properly in 1000 ms";
        }
        inst.second->deleteLater();
    }
    m_instanses.clear();
}
